package com.neuedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neuedu.common.BaseContext;
import com.neuedu.common.Result;
import com.neuedu.pojo.Address;
import com.neuedu.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /**
     * 添加地址
     *
     * @param address
     * @return
     */
    @PostMapping
    public Result<String> saveAddress(@RequestBody Address address) {

        // 设置用户id
        Long userId = BaseContext.getCurrentId();
        address.setUserId(userId);
        boolean isSaved = addressService.save(address);
        if (!isSaved) {
            return Result.error("添加地址失败");
        }
        return Result.success("添加地址成功");
    }

    /**
     * 修改地址
     *
     * @param address
     * @return
     */
    @PutMapping
    public Result<String> updateAddress(@RequestBody Address address) {
        boolean isUpdated = addressService.updateById(address);
        if (!isUpdated) {
            return Result.error("修改地址失败");
        }
        return Result.success("修改地址成功");
    }

    /**
     * 删除地址
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteAddressById(@PathVariable Long id) {
        boolean isDeleted = addressService.removeById(id);
        if (!isDeleted) {
            return Result.error("删除地址失败");
        }
        return Result.success("删除地址成功");
    }

    /**
     * 查询地址列表
     * @return
     */
    @GetMapping("/list")
    public Result<List<Address>> list() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId);
        List<Address> addresses = addressService.list();
        return Result.success(addresses);
    }
}
